<?php
class Cdn extends Module {
    private $base_url = '';
    private $base_dir = '';
    
    
    public function ajax_explorer() {
        $path = tos_http_get('path');
        $upload_path = 'upload/' . $path;
        
        $base_upload_dir = $this->base_dir . '/upload';
        
        $full_dir = $base_upload_dir . '/' . $path;
        
        if ( ! is_dir($full_dir)) {
            tos_die("cannot find dir $full_dir .");
        }
        
        $d = dir($full_dir);
        $files = array();
        $images = array();
        
        $folder_up_path = dirname($path);
        if (empty($folder_up_path) || $folder_up_path[0] == '.') $folder_up_path = '';
        
        $files['..'] = $folder_up_path;
        
        while (false !== ($entry = $d->read())) {
            if ($entry[0] === '.' || $entry[0] === '~') {
                continue;
            }
            $ext = pathinfo($entry, PATHINFO_EXTENSION);
            if ($ext == 'jpg' || $ext == 'png' || $ext == 'gif') {
                //$images[$entry] = trim($this->url($upload_path), '/') . '/' .$entry;
                $images[$entry] = trim($upload_path, '/') . '/' .$entry;
            }
            if (is_dir($full_dir . '/' . $entry)) {
                if (empty($path))
                    $files[$entry] = $entry;
                else {
                    $files[$entry] = $path . '/' .$entry;
                }
            }
            //$files[] = $entry;
        }
        
        $d->close();
        $view = $this->view('cdn/explorer', array('path' => $path, 'images'=>$images, 'files' => $files));
        $view->display();
//        print_r($files);
        return $files;
    }
    
    
    public function ajax_new_folder() {
        $folder = trim(tos_http_get("folder"), '/');
        if (empty($folder)) {
              echo 'error';
              //exit();
        } else {
            if (mkdir($this->base_dir . '/upload/' . $folder)) {
                echo 'ok';
            } else {
                echo 'error';
            }
        }
    }
    
    
    public function ajax_upload_img() {
        $path = tos_http_post('path');
        $full_dir = $this->base_dir . '/upload/' .trim($path, '/');
        if ( ! is_dir($full_dir)) {
            echo 'error path';
            return false;
        }
        
        if ( ! isset($_FILES['img_input_file'])) {
            echo 'no upload';
            return false;
        }
        
        $file = $_FILES['img_input_file'];
        $type = $file['type'];
        if ( ($type == "image/jpeg") || ($type == "image/pjpeg") 
            || ($type == "image/png") || ($type == "image/gif")) {
            if ($file["error"] > 0) {
                echo "Return Code: " . $file["error"] . "<br />";
              }
        }
        $name = $file['name'];
        $full_file = $full_dir . '/' . $name;
        if (move_uploaded_file($file["tmp_name"], $full_file)) {
            //echo $full_file;
            echo 'ok';
            return true;
        } else {
            echo 'failed';
            return false;
        }
    }
    
    
    public function ajax_img() {
        $src = tos_http_get('src');
        $width = (int) tos_http_get('width');
        $height = (int) tos_http_get('height');
        echo $this->_img($src, $width, $height);
    }
    
    public function set_opts($opts) {
        if (isset($opts['url'])) {
            $this->base_url = $opts['url'];
        }
        if (isset($opts['dir'])) {
            $this->base_dir = $opts['dir'];
        }
    }
    
    
    public function get_base_url() {
        return $this->base_url;
    }
    
    
    public function url($relative_url, $protocol = 'http') {
        $relative_url = trim($relative_url);
        return $protocol . '://' . $this->base_url . '/' . $relative_url;
    }
    
    
    public function img_src($src, $width = 0, $height = 0) {
    $src = trim($src);
        if (empty($src)) {
            return '';
        }
        $width = (int) $width;
        $height = (int) $height;
        
        if ($width == 0 && $height == 0) {
            return $img_src = "http://{$this->base_url}/{$src}";
        }else {
            $img_path = $this->base_dir . '/' . $src;
            $pathinfo = pathinfo($src);
            if ($width === 0 || $height === 0) {
                $size = getimagesize($img_path);
                if ($width === 0) {
                    $width = ceil($height * $size[0] / $size[1]);
                } else {
                    $height = ceil($width * $size[1] / $size[0]);
                }
            }
            //$new_src = 
            $new_img_dir = $this->base_dir . '/' . $pathinfo['dirname'] . '/' ."{$width}x{$height}";
            $new_img_path = $new_img_dir . '/' .$pathinfo['basename'];
            if ( ! file_exists($new_img_path)) {
                if ( ! is_dir($new_img_dir)) mkdir($new_img_dir);
                if ( ! $this->_resize_image($new_img_path, $img_path, $width, $height)) {
                    //tos_die();
                    return '';
                }
            }
            return $new_img_src = "http://{$this->base_url}/{$pathinfo['dirname']}/{$width}x{$height}/{$pathinfo['basename']}";
            
            //return "<img src=\"{$new_img_src}\" width=\"{$width}\" height=\"{$height}\"{$attr_str} />";
        }
    }
    
    
    public function img($src, $width = 0, $height = 0, $attributes = array()) {
        $src = trim($src);
        if (empty($src)) {
            return '';
        }
        $width = (int) $width;
        $height = (int) $height;
        
        
        $attr_str = '';
        if ($attributes) {
            $arr = array();
            foreach ($attributes as $k => $v) {
                $attr_str = " $k=\"$v\"";
            }
        }
        if ($width == 0 && $height == 0) {
            $img_src = "http://{$this->base_url}/{$src}";
            return "<img src=\"$img_src\"$attr_str />";
        }else {
            $img_path = $this->base_dir . '/' . $src;
            $pathinfo = pathinfo($src);
            if ($width === 0 || $height === 0) {
                $size = getimagesize($img_path);
                if ($width === 0) {
                    $width = ceil($height * $size[0] / $size[1]);
                } else {
                    $height = ceil($width * $size[1] / $size[0]);
                }
            }
            //$new_src = 
            $new_img_dir = $this->base_dir . '/' . $pathinfo['dirname'] . '/' ."{$width}x{$height}";
            $new_img_path = $new_img_dir . '/' .$pathinfo['basename'];
            if ( ! file_exists($new_img_path)) {
                if ( ! is_dir($new_img_dir)) mkdir($new_img_dir);
                if ( ! $this->_resize_image($new_img_path, $img_path, $width, $height)) {
                    //tos_die();
                    return '';
                }
            }
            $new_img_src = "http://{$this->base_url}/{$pathinfo['dirname']}/{$width}x{$height}/{$pathinfo['basename']}";
            
            return "<img src=\"{$new_img_src}\" width=\"{$width}\" height=\"{$height}\"{$attr_str} />";
        }
    }
    
    
    private function _resize_image($dest, $resc, $width, $height) {
        $im_dest = imagecreatetruecolor($width, $height);
        $im_resc;
        
        if ( ! file_exists($resc)) {
            return false;
        }
        
        $ext = strtolower(pathinfo($resc, PATHINFO_EXTENSION));
        if ($ext === 'png') {
            $im_resc = imagecreatefrompng($resc);
        } else if ($ext === 'jpg') {
            $im_resc = imagecreatefromjpeg($resc);
        } else if ($ext === 'gif') {
            $im_resc = imagecreatefromgif($resc);
        }
        if ( ! $im_resc) tos_die('resize image failed');
        
        list($resc_width, $resc_height) = getimagesize($resc);
        
        $white = imagecolorallocate($im_dest, 255, 255, 255);
        imagefilledrectangle($im_dest, 0, 0, $width, $height, $white);
        
        $new_width = $width;
        $new_height = $height;
        if ($resc_width > $resc_height) {
            $new_width = $width;
            $new_height = $width * $resc_height / $resc_width;
        } else {
            $new_height = $height;
            $new_width = $height * $resc_width / $resc_height;
        }
        /*$new_width = $width;
        $new_heigth = ceil($height * $resc_height / $resc_width);
        if ($new_height > $height) {
            $new_width = ceil();
        }*/
        
        imagecopyresampled($im_dest, $im_resc, ($width - $new_width) / 2, ($height - $new_height) / 2, 0, 0, $new_width, $new_height, $resc_width, $resc_height);
        imagedestroy($im_resc);
        
        /*$black = imagecolorallocate($im_dest, 0, 0, 0);
        imagecolortransparent($im_dest, $black);*/
        
        if ($ext === 'png') {
            imagepng($im_dest, $dest);
        } else if ($ext === 'jpg') {
            imagejpeg($im_dest, $dest);
        } else if ($ext === 'gif') {
            imagegif($im_dest, $dest);
        }
        
        
        
        imagedestroy($im_dest);
        return true;
    }
    
    /*public function set_base_url($base_url) {
        $this->base_url = $base_url;
    }
    
    
    public function set_base_dir($base_dir) {
        $this->base_dir = $base_dir;
    } */
}
?>